package com.sgb.kjwl.view.widget.transport.location;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgb.kjwl.model.entity.transport.AMapAddressEntity;
import com.sgb.link.R;
import com.sgb.link.databinding.CitySelectionLayoutBinding;
import com.sgb.link.entity.AddressItem;
import com.sgb.link.utils.AddressHelper;
import com.swgk.core.customview.WSTextView;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Describe:    城市选择器
 * Author:  yangLei
 * Date:    2021/7/29
 */
public class CitySelectionView extends RelativeLayout implements View.OnClickListener {

    private Context mContext;
    private CitySelectionLayoutBinding mBinding;

    private String currCity;
    //省市区三级地址列表
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 热门城市相关
     */
    private List<AMapAddressEntity> hotStrings;
    private WrapLinearLayout hotWrap;
    private SimpleTextAdapter textAdapter;
    private SortAdapter adapter;

    private WSTextView currCityTV;
    private RecyclerView hotCityGrid;

    /**
     * 汉字转换成拼音相关类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList = new ArrayList<>();
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private List<AddressItem> addressItems;

    public String getCurrCity() {
        return currCity;
    }

    public void setCurrCity(String currCity) {
        this.currCity = currCity;
        if (mBinding != null && currCityTV != null) {
            currCityTV.setText("当前城市：" + currCity);
        }
    }

    //事件相关
    private CityCheckedClickListener checkedClickListener;

    public CitySelectionView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater inflater = LayoutInflater.from(context);
        mBinding = DataBindingUtil.inflate(inflater, R.layout.city_selection_layout, this, true);
        this.mContext = context;
        initHot();
        initView();
        initData();
    }

    public CityCheckedClickListener getCheckedClickListener() {
        return checkedClickListener;
    }

    public void setCheckedClickListener(CityCheckedClickListener checkedClickListener) {
        this.checkedClickListener = checkedClickListener;
    }

    private void initHot() {
        hotStrings = new ArrayList<>();
        hotStrings.add(new AMapAddressEntity("北京", "110100", "110000"));
        hotStrings.add(new AMapAddressEntity("深圳", "440300", "440000"));
        hotStrings.add(new AMapAddressEntity("上海", "310100", "310000"));
        hotStrings.add(new AMapAddressEntity("广州", "440100", "440000"));
        hotStrings.add(new AMapAddressEntity("杭州", "330100", "330000"));
        hotStrings.add(new AMapAddressEntity("成都", "510100", "510000"));
        hotStrings.add(new AMapAddressEntity("重庆", "500100", "500000"));
    }

    /**
     * 初始化数据信息
     */
    private void initData() {
        if (addressEntityList == null) {
            getCityInfo();
        } else {
            initAddressData(addressEntityList);
        }
    }

    /**
     * 初始化所有组件
     */
    private void initView() {
        //头布局初始化
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.city_select_list_header_layout, null);
        currCityTV = headerView.findViewById(R.id.curr_city);
        hotCityGrid = headerView.findViewById(R.id.hot_city_grid);

        mBinding.sortListView.addHeaderView(headerView);

        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        mBinding.sideBar.setTextView(mBinding.dialog);
        hotCityGrid.setLayoutManager(new GridLayoutManager(mContext, 3));
        textAdapter = new SimpleTextAdapter(mContext, hotStrings);
        hotCityGrid.setAdapter(textAdapter);
        textAdapter.setItemClickListener((position, text) -> setResult(text));

        //设置右侧触摸监听
        mBinding.sideBar.setOnTouchingLetterChangedListener(s -> {
            //该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                mBinding.sortListView.setSelection(position);
            }

        });

        mBinding.sortListView.setOnItemClickListener((parent, view, position, id) -> {
            //这里要利用adapter.getItem(position)来获取当前position所对应的对象
            String cityNo = ((SortModel) adapter.getItem(position - 1)).getNo();
            AMapAddressEntity entity = new AMapAddressEntity(((SortModel) adapter.getItem(position - 1)).getName(),
                    cityNo, cityNo.substring(0, 2) + "0000");
            if (!TextUtils.isEmpty(entity.getCityNo()) && !TextUtils.isEmpty(entity.getCity())) {
                setResult(entity);
            }
        });

    }

    /**
     * 刷新城市列表数据
     */
    private void notifyCityList() {
        SourceDateList = filledData(addressItems);
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(mContext, SourceDateList);
        mBinding.sortListView.setAdapter(adapter);
    }

    /**
     * 为ListView填充数据
     *
     * @param data
     * @return
     */
    private List<SortModel> filledData(List<AddressItem> data) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < data.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(data.get(i).getAddressName());
            sortModel.setNo(data.get(i).getNo());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(data.get(i).getAddressName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    public void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.toUpperCase().indexOf(
                        filterStr.toUpperCase()) != -1
                        || characterParser.getSelling(name).toUpperCase()
                        .startsWith(filterStr.toUpperCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);

    }

    /**
     * 装载热门城市信息
     */
    private void loadGoodsSourceInfo(List<AMapAddressEntity> strings, WrapLinearLayout lay_gallery) {
        if (strings == null || strings.size() <= 0)
            return;
        lay_gallery.cleanItemListener();//先清除所有view的点击事件
        lay_gallery.removeAllViews();
        LayoutInflater mInflater = LayoutInflater.from(mContext);
        if (strings != null && strings.size() != 0) {
            for (int i = 0; i < strings.size(); i++) {
                final View view = mInflater.inflate(R.layout.item_hot_city_layout, lay_gallery, false);
                final TextView tv_info = view.findViewById(R.id.tv_info);
                tv_info.setText(strings.get(i).getCity());
                int finalI = i;
                tv_info.setOnClickListener(v -> setResult(strings.get(finalI)));
                lay_gallery.addView(view);
            }
        }
    }

    /**
     * 请求城市信息
     */
    private void getCityInfo() {
        AddressHelper.getInstance().getAllArea(new AddressHelper.CallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                if (data != null && data.size() > 0) {
                    initAddressData(data);
                } else {
                    MToast.showLongToast(mContext, "未获取到城市信息");
                }
            }

            @Override
            public void threeData(List<AddressEntity> provinceList, List<List<AddressEntity>> cityList, List<List<List<AddressEntity>>> districtList) {

            }
        });
    }

    /**
     * 初始化所有城市信息
     *
     * @param data
     */
    private void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (addressItems == null) {
            addressItems = new ArrayList<>();
        } else
            addressItems.clear();

        if (data.size() <= 0) {
            MToast.showToast(mContext, "获取城市列表失败");
            return;
        }

        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> datum : data) {
            if (datum.getChildren() != null && datum.getChildren().size() > 0) {
                for (AddressEntity<List<AddressEntity>> child : datum.getChildren()) {
                    if (!TextUtils.isEmpty(child.getSimpleName()))
                        addressItems.add(new AddressItem(child.getSimpleName(), child.getNo()));
                }
            }
        }

        //通知列表加载
        notifyCityList();
    }


    private void setResult(AMapAddressEntity entity) {
        currCity = entity.getCity();
//        MToast.showLongToast(mContext, "选择了" + currCity);
        if (checkedClickListener != null) {
            checkedClickListener.onCheckedResult(entity);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }


    public interface CityCheckedClickListener {

        void onCheckedResult(AMapAddressEntity addressEntity);
    }
}
